using B.S.XZYData.Api.Wrter.Application.Command.WorkReportDefectiveItem;
using DomainWorkReportDefectiveItem = B.S.XZYData.Domain.ZSH.WorkReportDefectiveItem;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;

namespace B.S.XZYData.Api.Wrter.Application.Handler.WorkReportDefectiveItem
{
    /// <summary>
    /// 导入报工-不良品项子表处理器
    /// </summary>
    public class ImportWorkReportDefectiveItemsHandler : IRequestHandler<ImportWorkReportDefectiveItemsCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<DomainWorkReportDefectiveItem> _defectiveItemRepo;

        public ImportWorkReportDefectiveItemsHandler(IBaseRepository<DomainWorkReportDefectiveItem> defectiveItemRepo)
        {
            _defectiveItemRepo = defectiveItemRepo;
        }

        public async Task<ApiResult<int>> Handle(ImportWorkReportDefectiveItemsCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<int>();

            if (request.Items == null || request.Items.Count == 0)
            {
                res.Code = ApiEnum.Fail;
                res.Msg = "导入数据不能为空";
                return res;
            }

            // 基本校验：WorkReportId > 0, DefectiveCode not empty, DefectiveQty > 0
            var invalid = request.Items.Where(i => i.WorkReportId <= 0 || string.IsNullOrWhiteSpace(i.DefectiveCode) || i.DefectiveQty <= 0).ToList();
            if (invalid.Any())
            {
                res.Code = ApiEnum.Fail;
                res.Msg = $"存在无效数据行，共{invalid.Count}条";
                return res;
            }

            try
            {
                using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);

                var entities = request.Items.Select(item => new DomainWorkReportDefectiveItem
                {
                    WorkReportId = item.WorkReportId,
                    DefectiveCode = item.DefectiveCode,
                    DefectiveQty = item.DefectiveQty,
                    CreateTime = DateTime.Now,
                    CreatorId = request.CreatorId,
                    IsDeleted = false
                }).ToList();

                var affectedRows = await _defectiveItemRepo.CreateBatchAsync(entities);

                scope.Complete();

                res.Code = ApiEnum.Success;
                res.Msg = "导入成功";
                res.Data = affectedRows;
                return res;
            }
            catch (Exception ex)
            {
                res.Code = ApiEnum.Error;
                res.Msg = $"导入异常：{ex.Message}";
                return res;
            }
        }
    }
} 